/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 *
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "elewise/kernel/elewise_kernel.h"
namespace {
using ADD_FLOAT = ATVC::OpTraits<ATVC::OpInputs<float, float>, ATVC::OpOutputs<float>>;
using ADD_INT = ATVC::OpTraits<ATVC::OpInputs<int, int>, ATVC::OpOutputs<int>>;

template<typename Traits>
struct TanhGradComputeFunc {
template<typename DTYPE_DY, typename DTYPE_X, typename DTYPE_Z>
__aicore__ inline void operator()(AscendC::LocalTensor<DTYPE_DY> dy, AscendC::LocalTensor<DTYPE_X> y,
    AscendC::LocalTensor<DTYPE_Z> z) {
    auto length = y.GetSize();
    AscendC::Mul(y, y, y, length);
    AscendC::Mul(y, dy, y, length);
    AscendC::Sub(z, dy, y, length);
}
};
}
template<class Traits>
/*
 * 该函数为Add算子核函数入口
 * a        Device上的gm地址，指向Add算子第一个输入
 * b        Device上的gm地址，指向Add算子第二个输入
 * c        Device上的gm地址，指向Add算子第一个输出
 * param    指向运行态ATVC::EleWiseParam数据
*/
__global__ __aicore__ void TanhGrad(GM_ADDR dy, GM_ADDR y, GM_ADDR z, ATVC::EleWiseParam param)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    auto op = ATVC::Kernel::EleWiseOpTemplate<TanhGradComputeFunc<Traits>>();  // 将TanhGradComputeFunc仿函数作为模板参数传入，实例化EleWiseOpTemplate模板类
    op.Run(dy, y, z, &param); // 按照输入、输出、param的顺序传入Run函数，实现GM->GM的数据计算
}

void TanhGradFloat(uint32_t blockDim, void* stream, uint8_t* dy, uint8_t* y, uint8_t* z, ATVC::EleWiseParam param) {
    TanhGrad<ADD_FLOAT><<<blockDim, nullptr, stream>>>(dy, y, z, param);
}

